package com.ara.common.kernel.base;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.ara.common.kernel.network.exception.NotNetException;
import com.ara.common.kernel.network.util.NetworkUtils;

import java.lang.ref.WeakReference;

import io.reactivex.rxjava3.disposables.CompositeDisposable;

/**
 * Created by XieXin on 2017-09-15.
 * Presenter的基类：MVP模式中的P层
 */

public abstract class BasePresenter<V extends BaseView> implements DefaultLifecycleObserver {
    /**
     * 弱引用对象，防止内存泄露
     */
    protected WeakReference<V> view;

    protected CompositeDisposable compositeDisposable;

    public BasePresenter(V view) {
        bind(view);
    }

    /**
     * 与View绑定
     */
    public void bind(V view) {
        if (compositeDisposable == null) compositeDisposable = new CompositeDisposable();
        this.view = new WeakReference<>(view);
    }

    /**
     * 获取View
     *
     * @return view
     */
    public V getView() {
        return view.get();
    }

    /**
     * 是否绑定
     *
     * @return true绑定
     */
    public boolean isBind() {
        return null != view && null != view.get();
    }

    /**
     * 解除与View的绑定
     */
    public void unbind() {
        if (compositeDisposable != null) {
            unSubscribe();
            compositeDisposable = null;
        }
        if (view != null) {
            view.clear();
            view = null;
        }
    }

    /**
     * 清除 订阅
     */
    public void unSubscribe() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }

    protected boolean isNotNet() {
        if (!NetworkUtils.isConnected()) {
            getView().onToast(NotNetException.create());
            getView().onError(0, NotNetException.create());
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        //防止内存泄露
        unbind();
    }
}
